package cn.wowjoy.office.materialinspection.xunjian.detail;

import android.arch.lifecycle.MediatorLiveData;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.common.adapter.DeviceDetailPhotoAdapter;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.request.InspectRecordControllerRequest;
import cn.wowjoy.office.data.response.InspectRecordControllerResponse;
import cn.wowjoy.office.data.response.InspectTaskSelect;
import cn.wowjoy.office.homepage.MenuHelper;
import cn.wowjoy.office.pm.data.UploadImgResponse;
import cn.wowjoy.office.utils.ImageFileParse;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

import static cn.wowjoy.office.data.constant.Constants.MEDIA_TYPE_JSON;

/**
 * Created by Administrator on 2017/11/1.
 */

public class DeviceDetailViewModel extends NewBaseViewModel {

    private MediatorLiveData<LiveDataWrapper<InspectRecordControllerResponse>> submit = new MediatorLiveData<>();
    private MediatorLiveData<LiveDataWrapper<InspectRecordControllerResponse>> submitByBroadcast = new MediatorLiveData<>();
    private MediatorLiveData<LiveDataWrapper<InspectTaskSelect>> selectDtl = new MediatorLiveData<>();
    public MediatorLiveData<LiveDataWrapper<InspectTaskSelect>> getSelectDtl() {
        return selectDtl;
    }

    public MediatorLiveData<LiveDataWrapper<InspectRecordControllerResponse>> getSubmitByBroadcast() {
        return submitByBroadcast;
    }

    public MediatorLiveData<LiveDataWrapper<InspectRecordControllerResponse>> getSubmit() {
        return submit;
    }

    @Inject
    ApiService apiService;

    @Inject
    public DeviceDetailViewModel(@NonNull NewMainApplication application) {
        super(application);
    }
    public List<Bitmap> mBitmaps;
    public DeviceDetailPhotoAdapter mDeviceDetailPhotoAdapter = new DeviceDetailPhotoAdapter();
    public DeviceDetailPhotoAdapter mDeviceDetailPhotoDoneAdapter = new DeviceDetailPhotoAdapter();


    public void setBitmaps(List<Bitmap> mLists) {
        if (null == mBitmaps) {
            mBitmaps = new ArrayList<>();
        }
        mBitmaps.clear();
        mBitmaps.addAll(mLists);
//        mDeviceDetailPhotoAdapter.setBitmaps(mLists);
//        photoAdapter.removeFooterView();
//        photoAdapter.removeHeaderView();
//        photoAdapter.notifyDataSetChanged();
    }

    public GlideUrl getGlideUrlHeaderUrl(String glideUrlHeader, String mToken) {
        GlideUrl glideUrl = null;
        if (!TextUtils.isEmpty(glideUrlHeader)) {
            glideUrl = new GlideUrl(glideUrlHeader, new LazyHeaders.Builder()
                    .addHeader("Content-Type", "application/json;charset=UTF-8")
                    .addHeader("Authorization", mToken)
                    .build());
        }
        return glideUrl;
    }
    private Map<String, RequestBody> initSaveInfo(InspectRecordControllerRequest request, List<String> filePaths){
        Gson gson = new Gson();

        Map<String, RequestBody> bodyMap = new ArrayMap<>();
        RequestBody bodyJson = RequestBody.create(MEDIA_TYPE_JSON, gson.toJson(request));
        bodyMap.put("inspectRecordDtlVO", bodyJson);
        bodyMap = ImageFileParse.typeTurn(filePaths,bodyMap,"file");
        return bodyMap;
    }
    private Map<String, RequestBody> initSaveInfo(List<String> filePath){
        Map<String, RequestBody> bodyMap = new ArrayMap<>();
        bodyMap = ImageFileParse.typeTurn(filePath,bodyMap,"file");
        return bodyMap;
    }
    public void submitInspectRecord(InspectRecordControllerRequest request){
        submit.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.uploadInspectRecordControllerInfo(request, MenuHelper.getAuidS().get("zc_inspect"))
                .flatMap(new ResultDataParse<>())
                .compose(new RxSchedulerTransformer<>())
                .subscribe((InspectRecordControllerResponse taskListResponse) -> {
                    submit.setValue(LiveDataWrapper.success(taskListResponse));
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        submit.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }

    /**
     *  二维码广播的默认提交
     * @param request
     */
    public void submitInspectRecordBroad(InspectRecordControllerRequest request){
        submitByBroadcast.setValue(LiveDataWrapper.loading(null));
//        Map<String, RequestBody> initSaveInfo = initSaveInfo(request ,FilePaths);
        Disposable disposable = apiService.uploadInspectRecordControllerInfo(request, MenuHelper.getAuidS().get("zc_inspect"))
                .flatMap(new ResultDataParse<>())
                .compose(new RxSchedulerTransformer<>())
                .subscribe((InspectRecordControllerResponse taskListResponse) -> {
                    submitByBroadcast.setValue(LiveDataWrapper.success(taskListResponse));
//                    if(null != waitDialog){
//                        CreateDialog.dismiss(mDeviceDetailActivity, waitDialog);
//                    }
//                    mDeviceDetailActivity.qrCode = qrCode;
//                    mDeviceDetailActivity.isDone = false;
//                    mDeviceDetailActivity.isShow = false;
//                    mDeviceDetailActivity.taskDtlId = null;
//                    mDeviceDetailActivity.mDeviceDetailPresenter.selectDtl(mDeviceDetailActivity.totalId,null,qrCode);
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        submitByBroadcast.setValue(LiveDataWrapper.error(throwable,null));
//                        if(null != waitDialog){
//                            CreateDialog.dismiss(mDeviceDetailActivity, waitDialog);
//                        }
//                        mDeviceDetailActivity.handleException(throwable, true);
                    }
                });
        addDisposable(disposable);
    }

    public void selectDtl(String taskId,String taskDtlId ,String qrCode){
        selectDtl.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.selectDtlPDA(taskId,taskDtlId,qrCode)
                .flatMap(new ResultDataParse<>())
                .compose(new RxSchedulerTransformer<>())
                .subscribe((InspectTaskSelect single) -> {
                    //TODO: 设置界面上的详细数据 着重区分下！！！ 已完成和未完成显示的页面区别
                    selectDtl.setValue(LiveDataWrapper.success(single));
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        selectDtl.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }
    //图片上传
    public MediatorLiveData<LiveDataWrapper<UploadImgResponse>> upload = new MediatorLiveData<>();
    public void uploadPic(List<String> FilePaths){
        upload.setValue(LiveDataWrapper.loading(null));
        Map<String, RequestBody> initSaveInfo = initSaveInfo(FilePaths);
        Disposable disposable = apiService.uploadSignName(initSaveInfo)
                .flatMap(new ResultDataParse<>())
                .compose(new RxSchedulerTransformer<>())
                .subscribe((UploadImgResponse taskListResponse) -> {
                    upload.setValue(LiveDataWrapper.success(taskListResponse));
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        upload.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }

    //直接获取的字节流
    public MediatorLiveData<LiveDataWrapper<ResponseBody>> photoAdd = new MediatorLiveData<>();
    public void getPhotoByte(String fileId){
        submit.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getPhotoByte(fileId)
                .flatMap(new ResultDataParse<>())
                .compose(new RxSchedulerTransformer<>())
                .subscribe((ResponseBody responseBody) -> {
                    photoAdd.setValue(LiveDataWrapper.success(responseBody));
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        photoAdd.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }


    //获取的url地址
    public MediatorLiveData<LiveDataWrapper<String>> photoUrl = new MediatorLiveData<>();
    public void getPhotoUrl(){
        photoUrl.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.preFileUrl()
                .flatMap(new ResultDataParse<>())
                .compose(new RxSchedulerTransformer<>())
                .subscribe((String responseBody) -> {
                    Log.e("PXY", "getPhotoUrl: "+responseBody );
                    photoUrl.setValue(LiveDataWrapper.success(responseBody));
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        photoUrl.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }

    @Override
    public void onCreateViewModel() {

    }
}
